import {
  getPage,
  getImage
} from '../../utils/config';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
import {
  promisify,
  http,
  $toast,
  utils,
  $query
} from '../../utils/utils';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPage: getPage,
    getImage: getImage,
    filterId: 1,
    filterType: 0,
    loading: 0,
    tabbarActive: 1,
    logged: 0,
    catsLoad: false,
    pageSize: 20,
    productIndex: 1,
    productIndexRes: 0,
    anliIndex: 1,
    anliIndexRes: 0,
    nextPage: true,
    orders: 'desc',
    userId: '',
    shopNo: '',
    loadmore: false,
    loaddone: false,
    abnor: false,
    imgheights: {},
    curBannerHeight: 0,
    showtips: 0,
    anliList: [],
    loadmore: true,
    loaddone: false,
    url: "",
    activeKey: 0,
    cateList: [],
    cid: 0,
    productList: [],
    imgheightsUser: {},
    imgheightsUserSeka: {},
    deignList: [],
    showCount: false,
    is_count: false,
    count_text: '你找Ta装修大概要花多少钱？',
    count_info: '输入你家房子的面积算一算吧',
    area_value: null,
    cur_type: null,
    cur_price: null,
    zx_typeOptions: [{
        id: 1,
        name: '半包'
      },
      {
        id: 2,
        name: '全包'
      },
      {
        id: 3,
        name: '全案'
      }
    ],
    jiaofuwuList: [{
        title: '全案预算清单',
        picurl: ['anli/m17219101640008649.jpg', 'anli/m17219103670001804.jpg']
      },
      {
        title: '平面图',
        picurl: ['anli/m17219103670001804.jpg']
      },
      {
        title: '效果图',
        picurl: ['anli/m17219099830006562.jpg']
      },
      {
        title: '效果图',
        picurl: ['anli/m17219096130006439.jpg']
      }
    ],
    isshow: false,
    tjlistShow: false,
    tjlist: [],
    sekalist: [],
    couponList: [],
    isShowCoupon: false,
    usershopid:'',
    sharehow:false,
    shareid:'',
    share_id:'',
    isShowService:false,
    isShopDescript:false,
    isCompanydesc:false,
    isGoodinstyle:false,
    showxq:false,
    xq_list:null
  },

  goChaXunPrice(e){
    let {item} = e.currentTarget.dataset;
    console.log('item===========',item)
    let {shopInfo} = this.data;
    wxApi.navigateTo(getPage.mfshejiprice,{
      type: 1,
      id:item.id,
      picurl:item.picurl,
      price:item.price,
      discount_price:item.discount_price,
      title:item.productname,

      receiver: shopInfo.UserId,

      gochat_id: shopInfo.ShopId,
      gochat_user_name: shopInfo.ShopName,
      gochat_img: shopInfo.picurl,
      gochat_touserid: shopInfo.UserId
    });
  },

  showCouponList() {
    this.setData({
      isShowCoupon: !this.data.isShowCoupon
    })
  },

  handlelqcoupon(e) {
    let cou_id = e.currentTarget.dataset.couponid;
    http.post(api.default, {
      data: {
        action: 'getshopcoupon',
        CouponId: cou_id,
        userid: this.data.userId
      }
    }, false).then(res => {
      console.log('res===', res)
      $toast('领取成功', {
        icon: 'success'
      });
      let {
        couponList
      } = this.data;
      couponList.forEach(item => {
        if (item.CouponId == cou_id) {
          item.MyReceivedNum = 1
        }
      })
      this.setData({
        couponList
      })
    })
  },

  showtjlist() {
    this.setData({
      tjlistShow: true
    })
  },
  ontjlistClose() {
    this.setData({
      tjlistShow: false
    })
  },
  canceltuijian(e) {
    var {
      logged,
      userId,
      shopid,
      isrecommend,
      tjlist
    } = this.data;
    let id = e.currentTarget.dataset.id;
    console.log('eeeeee', id)
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'del_shoprecommend',
          shopid: shopid,
          userid: userId
        }
      }, false).then(res => {
        $toast(`取消推荐成功`, {
          icon: 'success'
        });
        isrecommend = false;
        let res_tjlist = tjlist.filter(f => f.userid != userId)
        this.setData({
          tjlistShow: false,
          tjlist: res_tjlist,
          isrecommend: isrecommend
        });
      })
    } else {
      this.jumpLogin();
    }
  },
  imageLoad: function (e) { //获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  imageLoadUser: function (e) { //获取图片真实宽度 
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    let bol = ratio > 1 ? true : false
    var imgheightsUser = this.data.imgheightsUser;
    imgheightsUser[e.target.dataset.id] = bol;
    this.setData({
      imgheightsUser: imgheightsUser
    })
    // console.log('imgheightsUser',imgheightsUser)
  },
  imageLoadUserSeka: function (e) { //获取图片真实宽度 
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    let bol = ratio > 1 ? true : false
    var imgheightsUserSeka = this.data.imgheightsUserSeka;
    imgheightsUserSeka[e.target.dataset.id] = bol;
    this.setData({
      imgheightsUserSeka: imgheightsUserSeka
    })
    // console.log('imgheightsUser',imgheightsUser)
  },
  // 去色卡详情
  gosekadetail(e) {
    console.log('eeeeeeeeeeeeee')
    const data = e.currentTarget.dataset || e.target.dataset;
    wxApi.navigateTo(getPage.sekadetail, {
      seka_id: data.id
    });
  },
  // 去案例详情
  goanlidetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    if (data.id) {
      wxApi.navigateTo(getPage.anlidetail, {
        id: data.id,
        picurl: this.data.shopInfo.picurl,
        ShopName: this.data.shopInfo.ShopName,
        ShopId: this.data.shopInfo.ShopId,
        UserId: this.data.shopInfo.UserId,
        ShopType: this.data.shopInfo.ShopType
      });
    }
  },
  // 去设计详情
  godeigndetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    let {
      picurl,
      ShopName,
      ShopId,
      UserId,
      ShopType
    } = this.data.shopInfo;
    if (data.id) {
      wxApi.navigateTo(getPage.degindetail, {
        id: data.id,
        picurl,
        ShopName,
        ShopId,
        UserId,
        ShopType
      });
    }
  },
  // 去产品详情
  goproductdetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    if (data.id) {
      wxApi.navigateTo(getPage.productdetail, {
        id: data.id,
        // picurl:this.data.shopInfo.picurl,
        // ShopName:this.data.shopInfo.ShopName,
        // ShopId:this.data.shopInfo.ShopId,
        // UserId:this.data.shopInfo.UserId,
        // ShopType:this.data.shopInfo.ShopType
      });
    }
  },
  // 去交付物
  gojiaofuwu() {
    // let {
    //   jiaofuwuList
    // } = this.data;
    // let imgList = encodeURIComponent(JSON.stringify(jiaofuwuList))
    // wxApi.navigateTo(getPage.jiaofuwu, {
    //   imgList,
    // });
  },
  /**
   * 返回上一页
   */
  goBackTap() {
    //存在上一页,关闭当前返回一层,//没有上一页，跳回首页
    this.data.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.home);
  },
  updateDot(data) {
    let dots = data.detail.dots;
    this.setData({
      dots
    })
  },
  // 电话员工
  callphoneStaff(e) {
    let {
      name,
      tel
    } = e.currentTarget.dataset;
    if (!tel) return $toast('暂无电话');
    let {
      logged,
      showtips,
      contacters
    } = this.data;
    let _this = this;
    var itemList = [];
    itemList = [name + " " + tel]
    console.log('itemList', itemList)
    if (logged) {
      if (showtips == 0) {
        wx.showModal({
          title: '防骗提醒',
          content: '陌生电话要警惕，要求转账不要理',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              _this.setData({
                showtips: 1
              });
              wx.showActionSheet({
                itemList: itemList,
                success(res) {
                  console.log(res.tapIndex);
                  wx.makePhoneCall({
                    phoneNumber: tel, //此号码仅用于测试 。
                    success: function () {
                      console.log("拨打电话成功！")
                    },
                    fail: function () {
                      console.log("拨打电话失败！")
                    }
                  })
                },
                fail(res) {
                  console.log(res.errMsg)
                }
              })
            }
          }
        })
      } else {
        wx.showActionSheet({
          itemList: itemList,
          success(res) {
            console.log(res.tapIndex);
            wx.makePhoneCall({
              phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
              success: function () {
                console.log("拨打电话成功！")
              },
              fail: function () {
                console.log("拨打电话失败！")
              }
            })
          },
          fail(res) {
            console.log(res.errMsg)
          }
        })

        console.log(this.data.contacters)
      }
    } else {
      this.jumpLogin();
    }
  },
  callphone() {
    let {
      logged,
      shopInfo,
      showtips,
      contacters
    } = this.data;
    let _this = this;
    var itemList = [];
    contacters.forEach(element => {
      itemList.push(element.contacter + " " + element.tel);
    });
    if (logged) {
      if (showtips == 0) {
        wx.showModal({
          title: '防骗提醒',
          content: '陌生电话要警惕，要求转账不要理',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              _this.setData({
                showtips: 1
              });
              wx.showActionSheet({
                itemList: itemList,
                success(res) {
                  console.log(res.tapIndex);
                  wx.makePhoneCall({
                    phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
                    success: function () {
                      console.log("拨打电话成功！")
                    },
                    fail: function () {
                      console.log("拨打电话失败！")
                    }
                  })
                },
                fail(res) {
                  console.log(res.errMsg)
                }
              })
            }
          }
        })
      } else {
        wx.showActionSheet({
          itemList: itemList,
          success(res) {
            console.log(res.tapIndex);
            wx.makePhoneCall({
              phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
              success: function () {
                console.log("拨打电话成功！")
              },
              fail: function () {
                console.log("拨打电话失败！")
              }
            })
          },
          fail(res) {
            console.log(res.errMsg)
          }
        })

        console.log(this.data.contacters)
      }
    } else {
      this.jumpLogin();
    }
  },
  goParkingLot(e) {
    let {
      logged,
      shopInfo
    } = this.data;
    if (logged) {
      const latitude = shopInfo.Lat;
      const longitude = shopInfo.Lng;
      //打开内部地图（默认腾讯地图）
      wx.openLocation({
        latitude,
        longitude,
        scale: 18,
        name: shopInfo.Address2,
        address: shopInfo.Address
      })
    } else {
      this.jumpLogin();
    }
  },

  // 产品上拉加载更多数据
  loadMoreData: function () {
    let {
      productIndex,
      productIndexRes
    } = this.data;
    console.log('上拉加载更多数据--上拉加载更多数据', productIndexRes, productIndex)
    if (productIndexRes > productIndex) {
      productIndex++;
      this.setData({
        productIndex
      });
      this.getshopProductList((res) => {
        let {
          productList
        } = this.data;
        this.setData({
          productList: productList.concat(res.list),
        });
      });
    }
  },

  // 设计上拉加载更多数据
  loadMoreDataDes: function () {
    let {
      productIndex,
      productIndexRes
    } = this.data;
    console.log('上拉加载更多数据--上拉加载更多数据', productIndexRes, productIndex)
    if (productIndexRes > productIndex) {
      productIndex++;
      this.setData({
        productIndex
      });
      this.getDeignList((res) => {
        let {
          deignList
        } = this.data;
        this.setData({
          deignList1: deignList.concat(res.list),
        });
      });
    }
  },

  // 案例上拉加载更多数据
  loadMoreDataAnli: function () {
    let {
      anliIndex,
      anliIndexRes
    } = this.data;
    console.log('上拉加载更多数据--上拉加载更多数据', anliIndexRes, anliIndex)
    if (anliIndexRes > anliIndex) {
      anliIndex++;
      this.setData({
        anliIndex
      });
      this.getAnliList((res) => {
        let {
          anliList
        } = this.data;
        this.setData({
          anliList: anliList.concat(res.list),
        });
      });
    }
  },

  gotousu() {
    let {
      logged,
      shopInfo
    } = this.data;
    if (logged) {
      wxApi.navigateTo(getPage.tousu + "?id=" + shopInfo.ShopId + "&name=" + shopInfo.ShopName + "&type=商家" + "&title=" + shopInfo.ShopName);
    } else {
      this.jumpLogin();
    }
  },
  /**
   * 电赞案例
   */
  followAnliClick(event) {
    let {
      xqid
    } = event.currentTarget.dataset
    var {
      logged,
      userId,
    } = this.data;
    console.log('xqid==========',xqid)
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'like_xuqiu',
          userid: userId,
          id: xqid,
        }
      }).then((res) => {
        let {errmsg,data} = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        // 前端显示跟新收藏状态
        let anliArr = this.data.anliList;
        anliArr.forEach(item => {
          if (item.id == xqid) {
            item.is_like = data,
            item.likes_num = data?item.likes_num+1:item.likes_num-1
          }
        })
        this.setData({
          anliList: anliArr
        })
      })
    } else {
      this.goLogin();
    }
  },
  /**
   * 关注店铺
   */
  followClick() {
    var {
      logged,
      userId,
      shopid,
      is_fav_shop,
      fans
    } = this.data;
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'fav_shop',
          userid: userId,
          shopid: shopid,
        }
      }).then((res) => {
        let {
          errmsg,
          data
        } = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        // fans = fans + 1;
        this.setData({
          // fans: fans,
          is_fav_shop: data
        });
      })
    } else {
      this.jumpLogin();
    }
  },
  /**
   * 推荐店铺
   */
  goodjobClick() {
    var {
      logged,
      userId,
      shopid,
      tjlist,
      loc_shopId,
      loc_picurl,
      loc_ShopName
    } = this.data;
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'shoprecommend',
          userid: userId,
          shopid: shopid,
        }
      }).then((res) => {
        let {
          errmsg,
          data
        } = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        if (data) {
          let tj_user = {
            head_url: loc_picurl,
            nickname: loc_ShopName,
            shopid: loc_shopId,
            userid: userId,
          }
          tjlist.push(tj_user)
        } else {
          console.log('tjlist==', tjlist)
          tjlist = tjlist.filter(f => f.userid != userId)
        }
        this.setData({
          isrecommend: data,
          tjlist
        });
      })
    } else {
      this.jumpLogin();
    }
  },

  /**
   * 跳转登录页
   */
  jumpLogin() {
    wxApi.setStartPage({
      id: this.data.shopid
    });
    wxApi.navigateTo(getPage.login);
  },


  /**
   * 监听页面--滚动
   */
  scrollChange(e) {

  },
  onPreviewImage(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    var showmenu = true;
    const {
      anlilist
    } = this.data;
    console.log(data.index)
    const item = anlilist[data.index];
    console.log(anlilist.map((item) => item.picurl));
    wx.previewImage({
      urls: anlilist.map((item) => api.imageCdn + item.picurl),
      current: api.imageCdn + item.picurl,
      showmenu,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  gochat() {
    var {
      logged,
      shopInfo
    } = this.data;
    console.log(logged);
    if (logged) {
      console.log(getPage.PrivateChat + `?conversationID=C2C${shopInfo.UserId}`);
      wxApi.navigateTo(getPage.chat, {
        id: shopInfo.ShopId,
        user_name: shopInfo.ShopName,
        img: shopInfo.picurl,
        touserid: shopInfo.UserId
      });

    } else {
      this.jumpLogin();
    }
  },
  // 私聊员工
  gochatStaff(e) {
    var {
      logged
    } = this.data;
    var {
      id,
      userid,
      name,
      picurl
    } = e.currentTarget.dataset;
    console.log(logged);
    if (logged) {
      wxApi.navigateTo(getPage.chat, {
        user_name: name,
        img: picurl,
        touserid: userid
      });

    } else {
      this.jumpLogin();
    }
  },
  govr() {
    let {
      url
    } = this.data;
    if (url == "" || url == null)
      $toast("该店铺还未开通此服务！")
    else
      wxApi.navigateTo("/pages/web/web?id=" + url);
  },
  goanli(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    if (data.id) {
      wxApi.navigateTo("/pages/web/web?id=" + api.domain + "anli.aspx$id^" + data.id);
    }
  },

  onCateChange(e) {
    console.log('打印切换产品分类时', e)
    let ID = 0;
    if (e.detail > 0) {
      let {
        cateList
      } = this.data;
      ID = cateList[e.detail - 1].ID;
    }
    console.log('selectCate____________', ID)
    this.setData({
      cid: ID,
      productIndex: 1
    })
    this.getshopProductList((res) => {
      this.setData({
        productList: res.list
      });
    });
  },

  /**
   * getshopcategory  获取店铺分类
   *shopid   店铺ID
   */
  getcategory(cb, a = false) {
    let {
      shopid
    } = this.data;
    http.post(api.default, {
      data: {
        action: 'getshopcategory',
        shopid: shopid,
      }
    }, a).then(res => {
      this.setData({
        cateList: res.data.data
      })
      console.log('分类数据---------', res)
    })
  },

  // getdeignlist   获取设计作品列表
  // pageindex  当前页码
  // shopid   店铺ID

  getDeignList(cb) {
    let {
      shopid,
      productIndex
    } = this.data;
    http.post(api.default, {
      data: {
        action: 'getdeignlist',
        pageindex: productIndex,
        shopid: shopid
      }
    }, false).then(res => {
      const {
        data
      } = res.data;
      console.log('dataaaaaaaaaa', data)
      this.setData({
        productIndexRes: data.pages
      });
      cb && cb(data);
    })
  },

  /**
   * getshopproducts    获取店铺商品列表
   *pageindex  当前页码
   *shopid  店铺ID
   *cid  分类ID,不传或者0则显示全部产品
   */
  getshopProductList(cb) {
    let {
      shopid,
      cid,
      productIndex
    } = this.data;
    http.post(api.default, {
      data: {
        action: 'getshopproducts',
        pageindex: productIndex,
        shopid: shopid,
        cid
      }
    }, false).then(res => {
      const {
        data
      } = res.data;
      this.setData({
        productIndexRes: data.pages
      });
      cb && cb(data);
    })
  },

  /**
   * 获取商品--网络请求
   */
  getAnliList(cb) {
    let {
      anliIndex,
      shopid
    } = this.data;
    http.post(api.default, {
      data: {
        action: 'GetAnliList',
        pageindex: anliIndex,
        shopid: shopid,
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      this.setData({
        anliIndexRes: data.pages
      });
      cb && cb(data);
    });
  },
  gofwdetail(e) {
    let shopInfo = encodeURIComponent(JSON.stringify(e.currentTarget.dataset.shopinfo))
    wxApi.navigateTo(getPage.fwdetail, {
      id: e.currentTarget.dataset.id,
      shopInfo: shopInfo
    });
  },
  gopingjia(e) {
    wxApi.navigateTo(getPage.pingjia, {
      id: e.currentTarget.dataset.id
    });
  },
  gofwdetailprice(e) {
    wxApi.navigateTo(getPage.fwdetail_price, {
      id: e.currentTarget.dataset.id
    });
  },
  shareClose(){
    this.setData({
      sharehow:false
    })
  },
  goShare(){
    app.getLogin().then((res) => {
      console.log('rrrrrrrr',res)
      this.setData({
        userInfo: res,
        logged: res.code,
        userId: res.data.user.user_id,
        shopid: res.data.shop?.ShopId
      });
      http.post(api.default, {
        data: {
          action: 'addshopshare',
          userid: this.data.userId,
          shopid: this.data.shopid || 0
        }
      }, false).then(res=>{
        let {data} = res.data;
        this.setData({
          sharehow:true,
          share_id:data.id
        })
      })
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    });
  },
  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  handleShowMoreService(){
    let {isShowService} = this.data;
    this.setData({
      isShowService:!isShowService
    })
  },
  handleShowShopDescript(){
    let {isShopDescript} = this.data;
    this.setData({
      isShopDescript:!isShopDescript
    })
  },
  handleShowGoodinstyle(){
    let {isGoodinstyle} = this.data;
    this.setData({
      isGoodinstyle:!isGoodinstyle
    })
  },
  handleShowCompanydesc(){
    let {isCompanydesc} = this.data;
    this.setData({
      isCompanydesc:!isCompanydesc
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.hideShareMenu();

    /**
     * 店铺id
     */
    console.log('options-------------------', options)
    if (JSON.stringify(options) !== '{}') {
      this.setData({
        shopid: options.id,
        shareid: options.shareid||'',
        distance: options.distance * 1
      });
    }
    //获取路由数量
    this.setData({
      getPages: getCurrentPages().length
    })
    /**
     * 获取system信息
     */
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
      console.log(this.data.window);
    });

    /**
     * 获取用户信息 
     */
    let logged, userId = '';
    let loc_shopId, loc_picurl, loc_ShopName,usershopid = '';
    app.getLogin().then((res) => {
      console.log('getLogin======', res);
      logged = res.code;
      userId = res.data.user.user_id;
      loc_shopId = res.data.shop.ShopId;
      loc_picurl = res.data.shop.picurl;
      loc_ShopName = res.data.shop.ShopName;
      usershopid = res.data.shop.ShopId||'';
      this.setData({
        usershopid
      })
    }).catch((res) => {
      logged = res;
    }).finally(() => {
      this.setData({
        logged,
        userId,
        loc_shopId,
        loc_picurl,
        loc_ShopName
      });
      /**
       * 获取店铺信息
       */
      let {
        shopid,
        shareid,
        usershopid,
        pageSize,
        loaddone,
        abnor
      } = this.data;

      //第一部分数据加载
      http.post(api.default, {
        data: {
          action: 'getshopinfo',
          shopid: shopid,
          shareid: shareid,
          userid: userId,
          usershopid:usershopid
        }
      }, false).then((res) => {
        const {
          data
        } = res.data;
        console.log('getshopinfo===============onload>',data);
        let tabNamA = '公司团队'
        switch (data.shop.ShopType) {
          case 2:
            tabNamA = '主营产品';
            break;
          case 4:
            tabNamA = '设计作品';
            break;
          default:
            tabNamA = '公司团队';
        }
        let zx_typeOptions = this.data.zx_typeOptions;
        if (data.shop.banbao == 0) {
          zx_typeOptions = zx_typeOptions.filter(f => f.name != '半包')
        } else {
          zx_typeOptions.forEach(i => {
            if (i.name == '半包') i['price'] = data.shop.banbao
          })
        }
        if (data.shop.quanbao == 0) {
          zx_typeOptions = zx_typeOptions.filter(f => f.name != '全包')
        } else {
          zx_typeOptions.forEach(i => {
            if (i.name == '全包') i['price'] = data.shop.quanbao
          })
        }
        if (data.shop.quanan == 0) {
          zx_typeOptions = zx_typeOptions.filter(f => f.name != '全案')
        } else {
          zx_typeOptions.forEach(i => {
            if (i.name == '全案') i['price'] = data.shop.quanan
          })
        }
        let min_price = [data.shop.pingceng, data.shop.bieshu, data.shop.zijianfang, data.shop.fushi];
        let m_price = 0;
        try {
          min_price.forEach(item => {
            if (item) {
              m_price = item.split('-')[0]
              throw new Error()
            }
          })
        } catch (err) {
          console.log('error')
        }
        let cur_type = zx_typeOptions.length > 0 ? zx_typeOptions[0].id : null;
        let cur_price = zx_typeOptions.length > 0 ? zx_typeOptions[0].price : null;

        let count_text = '';
        let count_info = '';
        let is_count = '';
        if (data.zhuangxiucost) {
          count_text = `你找Ta做${['','半包','全包','全案'][data.zhuangxiucost.type]}大概要花${(data.zhuangxiucost.amount/10000).toFixed(0)}万元`;
          count_info = `最低平米造价为${m_price}元/m²，属于当地${data.zhuangxiucost.dangci}水平`;
          is_count = true;
        }
        console.log('-------', data.coupon)

        data?.coupons.forEach(item => {
          item.begintime = item.begintime.slice(0, 10)
          item.endtime = item.endtime.slice(0, 10)
        })
        let banner = [{adimg:'xuqiu/m17296676780005367.jpg'}]
        if(data.banner.length>0) banner = data.banner

        this.setData({
          score: data.score,
          pj: data.pj,
          pj_num: data.pj_num,
          tabNamA,
          shopInfo: data.shop,
          zhuangxiucost: data.zhuangxiucost,
          swiper: banner,
          is_fav_shop: data.is_fav_shop,
          isrecommend: data.isrecommend,
          fans: data.fans,
          loading: 1,
          contacters: data.contacters,
          anlilist: data.anlilist,
          content: data.des,
          url: data.shop.vr_url,
          zx_typeOptions,
          cur_type,
          cur_price,
          min_price,
          m_price,
          count_text,
          count_info,
          is_count,
          isshow: data.shop.ShopType == 2 ? false : true,
          showtab: true,
          tjlist: data.recommend_list,
          sekalist: data.sekalist,
          couponList: data.coupons,
          parent:data.parent || '',
          showxq:data.showxq,
          xq_list:data.xq_list || null
        });
        if (data.shop.ShopType != 4) {
          // 获取分类
          this.getcategory();
          // 获取商品
          this.getshopProductList((res) => {
            this.setData({
              productList: res.list
            });
          });
        } else {
          // 获取设计作品
          this.getDeignList((res) => {
            this.setData({
              deignList: res.list
            });
          })
        }
      });
    });

    // 获取案例
    this.getAnliList(
      (res) => {
        this.setData({
          anliList: res.list
        });
      }
    );
    /**
     * scrollTop
     */
    this.scrollTop = 0;
    this.scrollHeight = 0;

    /**
     * 获取收缩对象高度
     */
    $query.select('#headInfo', (data) => {
      this.headInfo = data;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showLoading({
      title: '加载中...',
    })

    let {
      shopid,
      userId,
      usershopid
    } = this.data;

    //第一部分数据加载
    http.post(api.default, {
      data: {
        action: 'getshopinfo',
        shopid: shopid,
        userid: userId,
        usershopid: usershopid
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      console.log('getshopinfo===============>',data);
      data?.coupons.forEach(item => {
        item.begintime = item.begintime.slice(0, 10)
        item.endtime = item.endtime.slice(0, 10)
      })
      let banner = [{adimg:'xuqiu/m17296676780005367.jpg'}]
      if(data.banner.length>0) banner = data.banner
      this.setData({
        shopInfo: data.shop,
        swiper: banner,
        is_fav_shop: data.is_fav_shop,
        isrecommend: data.isrecommend,
        fans: data.fans,
        loading: 1,
        contacters: data.contacters,
        anlilist: data.anlilist,
        content: data.des,
        url: data.shop.vr_url,
        tjlist: data.recommend_list,
        sekalist: data.sekalist,
        couponList: data.coupons,
        parent:data.parent || ''
      });
      if (data.shop.ShopType != 4) {
        // 获取分类
        this.getcategory();
        // 获取商品
        this.getshopProductList((res) => {
          this.setData({
            productList: res.list
          });
        });
      } else {
        // 获取设计作品
        this.getDeignList((res) => {
          this.setData({
            deignList: res.list
          });
        })
      }
    });


    // 获取案例
    this.getAnliList(
      (res) => {
        this.setData({
          anliList: res.list
        });
      }
    );
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }, 300)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  showImg(e) {
    let url = api.imageCdn + e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url],
      current: url,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },

  handleShowCount() {
    this.setData({
      showCount: true
    })
  },

  onCountClose() {
    let {
      zx_typeOptions
    } = this.data
    this.setData({
      showCount: false,
      cur_type: zx_typeOptions.length > 0 ? zx_typeOptions[0].id : null,
      cur_price: zx_typeOptions.length > 0 ? zx_typeOptions[0].price : null,
      area_value: null
    })
  },

  // 选择装修模式
  selectType(e) {
    let id = e.currentTarget.dataset.id;
    let price = e.currentTarget.dataset.price;
    console.log('price', price)
    this.setData({
      cur_type: id,
      cur_price: price
    })
  },

  // 面积输入框
  bindAreaChange: function (res) {
    this.setData({
      area_value: res.detail.value,
    })
  },

  // 计算价格
  handleCountPrice() {
    let that = this;
    let {
      shopid,
      userId,
      area_value,
      cur_type,
      m_price
    } = this.data;
    console.log('计算价格===', area_value, cur_type)

    let parms = {
      action: 'zhuangxiucost',
      userid: userId,
      shopid: shopid,
      mianji: area_value,
      type: cur_type,
    }
    http.post(api.default, {
      data: parms
    }).then(res => {
      let {
        data
      } = res.data;
      let count_text = `你找Ta做${['','半包','全包','全案'][data.type]}大概要花${(data.amount/10000).toFixed(0)}万元`;
      let count_info = `最低平米造价为${m_price}元/m²，属于当地${data.dangci}水平`
      that.setData({
        is_count: true,
        count_text,
        count_info
      })
    })
    this.onCountClose();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log('res===========',res)
    var pageshare = getPage.companydetail + "?id=" + this.data.shopid + "&shareid=" + this.data.share_id;
    console.log('pageshare', pageshare);
    console.log(api.imageCdn + this.data.shopInfo.picurl);
    this.setData({
      sharehow:false
    })
    // http.post(api.default, {
    //   data: {
    //     action: 'addshopshare',
    //     userid: this.data.userId,
    //     shopid: this.data.shopid
    //   }
    // }, false)
    return {
      title: `【可居】${this.data.shopInfo.ShopName}`,
      imageUrl: api.imageCdn + this.data.shopInfo.picurl,
      path: pageshare,
    }
  }
})